package org.itboys.mobile.service.mongo.weixin;


import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.project.ZhongBaoProjectDto;
import org.itboys.mobile.entity.ZhongBaoTag;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.ZhongBaoMessage;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProject;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProjectEmployee;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProjectImage;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProjectInfo;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：众包_微信_项目_service
 */
@Service
public class ZhongBaoWeiXinProjectService extends BaseMongoService<ZhongBaoProject> {

    @Autowired
    private SundayWeiXinMemberService memberService;
    @Autowired
    private ZhongBaoWeiXinProjectImageService projectImageService;
    @Autowired
    private ZhongBaoWeiXinProjectEmployeeService projectEmployeeService;
    @Autowired
    private ZhongBaoWeiXinProjectInfoService projectInfoService;
    @Autowired
    private ZhongBaoWeiXinMessageService messageService;
    @Autowired
    private ZhongBaoWeiXinProjectSignService signService;
    @Autowired
    private ZhongBaoWeiXinChatGroupService chatGroupService;
    @Autowired
    private ZhongBaoWeiXinTagService tagService;
    @Autowired
    private ResourceHolder resourceHolder;



    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<ZhongBaoProject> getEntityClass() {
        return ZhongBaoProject.class;
    }


    /**
     * 新增项目
     * @param id
     * @param memberId
     * @param name
     * @param keyWords
     * @param startDate
     * @param endDate
     * @param desc
     * @param images
     * @param employeeIds
     */
    public void addProject(long id, Long memberId, String name, String keyWords, Date startDate, Date endDate, String desc,Integer type, List<String> images,List<Long> employeeIds,
                           //标签的信息
                           String trade, Long provinceId, String provinceName, Long cityId, String cityName, String name1, String name2, String name3
                           ){
            ZhongBaoProject project= new ZhongBaoProject();
             SundayMember member =memberService.getById(memberId);
             project.setId(id);
             project.setMemberId(memberId);
             project.setMemberName(member.getNickName());
             project.setMemberMobile(member.getMobile());

             project.setName(name);
             project.setKeyWords(keyWords);
             project.setStartDate(startDate);
             project.setEndDate(endDate);
             project.setDesc(desc);
             project.setType(type);
             project.setStatus(SundayCommonConstants.zhongbao_project_status_ysh);
            boolean isNeedHandle=false;
            //用户为商户且为员工身份时，需要开启审核
            if(member.getUserType()==SundayCommonConstants.user_type_business&&
                    LongUtil.isNotZreo(member.getParentId())){
                    project.setStatus(SundayCommonConstants.zhongbao_project_status_dsh);
                 isNeedHandle=true;
            }
            super.save(project);
            //保存图片
            projectImageService.saveImages(project.getId(),images);
            //保存员工
            projectEmployeeService.saveEmployees(project.getId(),employeeIds);
            //创建标签
            tagService.saveTag(0l,  project.getId(),  trade,  provinceId,  provinceName,  cityId,  cityName,  name1,  name2,  name3);


            //需要审核
            if(isNeedHandle){
                //创建审核消息
                super.update(project.getId(),"handlerId",member.getParentId());
                messageService.generateMessage(member.getParentId(),memberId,project.getId(),SundayCommonConstants.zhongbao_message_type_apply,project.getName(),project.getName(),project.getId(),null);
            //不需要审核
            }else{
                //根据项目标签创建消息通知
                //创建聊天组。发布人和员工
                String memberIdStrs ="";
                    memberIdStrs+=String.valueOf(memberId)+",";
                    for(Long employeeId:employeeIds){
                        memberIdStrs+=String.valueOf(employeeId)+",";
                }
                memberIdStrs=memberIdStrs.substring(0,memberIdStrs.length()-1);
                long chatGroupId=chatGroupService.generateGroup(null,null,project.getId(),memberIdStrs);
                super.update(project.getId(),"chatGroupId",chatGroupId);
            }
    }

    /**
     * 项目审核
     * @param id
     * @param memberId
     * @param name
     * @param keyWords
     * @param startDate
     * @param endDate
     * @param desc
     * @param type
     * @param images
     * @param employeeIds
     */

    public void handle(long id, Long memberId, String name,
                       String keyWords, Date startDate, Date endDate,
                       String desc,Integer type, List<String> images,
                       List<Long> employeeIds,boolean isAgree,
                      //标签的信息
                      String trade, Long provinceId, String provinceName, Long cityId, String cityName, String name1, String name2, String name3
){
       // ZhongBaoProject project= super.getById(id);
        //驳回项目
        ZhongBaoProject project= super.getById(id);
        if(!isAgree){
          //  ZhongBaoProject project= super.getById(id);
         //   project.setStatus(SundayCommonConstants.zhongbao_project_status_ybh);
            super.update(id,"status",SundayCommonConstants.zhongbao_project_sign_ybh);
            //创建审核驳回消息
            messageService.generateMessage(project.getMemberId(),memberId,id,SundayCommonConstants.zhongbao_message_type_refuse,"项目【"+name+"】申请申请被驳回,","项目【"+name+"】申请申请被驳回",id,null);
        }else{

            SundayMember member =memberService.getById(project.getMemberId());
            project.setId(id);
            project.setMemberId(project.getMemberId());
            project.setMemberName(member.getNickName());
            project.setMemberMobile(member.getMobile());
            project.setName(name);
            project.setKeyWords(keyWords);
            project.setStartDate(startDate);
            project.setEndDate(endDate);
            project.setDesc(desc);
            project.setType(type);
            project.setStatus(SundayCommonConstants.zhongbao_project_status_ysh);
            super.updateExceptEmpty(id,project);
            //保存图片
            projectImageService.saveImages(project.getId(),images);
            //保存员工
            projectEmployeeService.saveEmployees(project.getId(),employeeIds);
            //创建标签
            tagService.saveTag(0l,  project.getId(),  trade,  provinceId,  provinceName,  cityId,  cityName,  name1,  name2,  name3);
            //创建审核通过消息通知
            messageService.generateMessage(project.getMemberId(),memberId,project.getId(),SundayCommonConstants.zhongbao_message_type_pass,project.getName()+"审核通过",project.getName()+"审核通过",project.getId(),null);

            //根据项目标签创建消息通知
            //创建聊天组。发布人和员工
            String memberIdStrs ="";
            memberIdStrs+=String.valueOf(memberId)+",";
            memberIdStrs+=String.valueOf(project.getMemberId())+",";
            for(Long employeeId:employeeIds){
                memberIdStrs+=String.valueOf(employeeId)+",";
            }
            memberIdStrs=memberIdStrs.substring(0,memberIdStrs.length()-1);
            long chatGroupId=chatGroupService.generateGroup(null,null,project.getId(),memberIdStrs);
            if(!LongUtil.isNotZreo(chatGroupId)){
                super.update(project.getId(),"chatGroupId",chatGroupId);
            }
        }
        //消息已读
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("status",SundayCommonConstants.NO);
        param.put("type",SundayCommonConstants.zhongbao_message_type_apply);
        List<ZhongBaoMessage> messages =messageService.list(param);
        for(ZhongBaoMessage message:messages){
            message.setStatus(SundayCommonConstants.YES);
        }
        messageService.batchUpdateWithoutLogin(messages);
    }
    /**
     * 分页获取项目。
     * @param request
     * @param memberId
     * @param type
     * @return
     */
    public List<ZhongBaoProjectDto>  getProjects(HttpServletRequest request,Long memberId,Integer type){
        Map<String,Object> param=new HashMap<String,Object>();
        Map<String,String> containsparam= ParamUtil.packageMongoVagueParam(request,"keyWords","name");
       // List<ZhongBaoProjectDto> dtos = null;
        SundayMember member=memberService.getById(memberId);
        List<ZhongBaoProject> projects=null;
         // List<>
        //1，自己关注的项目，2团体项目，3其他项目
        param.put("isDeleted", SundayCommonConstants.NO);

        //1,自己关注的项目
        if(type==1){
           param.put("id in",projectInfoService.getProjectIds(memberId,2));
        //2,团队项目(1，个人版获取自己的项目，2企业版获取)
        }else if(type==2){
            List<Long> memberIds = new ArrayList<>();
            memberIds.add(0l);

            //判断登陆人是否是管理员且为商户
            if(member.getUserType()==SundayCommonConstants.user_type_business){
                //查询登陆人的下属或同一上级下的所有人员
                Map<String,Object> param2=new HashMap<String,Object>();
                param2.put("isDeleted",SundayCommonConstants.NO);
                param2.put("userType",SundayCommonConstants.user_type_business);
                    //管理者
                    if(LongUtil.isZreo(member.getParentId())){
                        param2.put("parentId",member.getId());
                        //自己的项目
                        memberIds.add(memberId);
                    //员工
                    }else{
                        param2.put("parentId",member.getParentId());
                        //包含员工管理者的项目
                        memberIds.add(member.getParentId());
                    }
                List<SundayMember> employees=memberService.list(param2);

                if(ListUtil.isNotNull(employees)){
                    for(SundayMember employee:employees){
                        memberIds.add(employee.getId());
                    }
                }
            //个人版
            }else if(member.getUserType()==SundayCommonConstants.user_type_person){
                 memberIds.add(memberId);
            }
        //查询项目
        param.put("memberId in",memberIds);
        //公共项目
        }else if(type==3){
            //3.1,不能获取对内项目
            param.put("type",SundayCommonConstants.zhongbao_project_public);
            //3.2,只获取已审核的项目(进行中)
            param.put("status",SundayCommonConstants.zhongbao_project_status_ysh);

           // projects=super.containpageQuery(request,containsparam,param).getData();

        }
       // if(ListUtil.isNotNull(dtos)){
        return packageMuilt(super.containpageQuery(request,containsparam,param).getData(),memberId,false);
        //}
       // return null;
    }
    /**
     * 获取项目详情
     * @param projectId
     * @param memberId
     * @return
     */
    public ZhongBaoProjectDto  getProjectDetail(Long projectId,Long memberId){
        ZhongBaoProjectDto dto =null;
        if(LongUtil.isZreo(projectId)){
            dto= new ZhongBaoProjectDto();
            dto.setId(0l);
            return dto;
        }
        dto = packageSingle(super.getById(projectId));
        String imgRoot = resourceHolder.getStringValue("imgRoot");
        Map<String,Object> param=new HashMap<String,Object>();
        //装载项目图片
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("projectId",projectId);
        List<ZhongBaoProjectImage> images = projectImageService.list(param);
        for(ZhongBaoProjectImage image:images){
            image.setUrl(imgRoot+image.getUrl());
        }
        dto.setImages(images);
        //获取转发、关注的信息
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("projectId",projectId);
        param.put("order","desc");
        param.put("sort","ct");
        List<ZhongBaoProjectInfo> infos = projectInfoService.list(param);
        for(ZhongBaoProjectInfo info:infos){
            info.setMemberImage(imgRoot+info.getMemberImage());
        }
        //校验是否转发、关注
        Integer isSpread=0;
        Integer isCollection=0;

        //不是自己发布的项目， 才校验是否转发、报名、关注
   //  if(dto.getMemberId().longValue()!=memberId.longValue()){
        for(ZhongBaoProjectInfo info:infos){
            if(LongUtil.isNotZreo(info.getMemberId())&&
                    info.getMemberId().longValue()==memberId.longValue()){
                if(info.getType()==SundayCommonConstants.zhongbao_project_info_spread){
                    isSpread=1;
                }

                if(info.getType()==SundayCommonConstants.zhongbao_project_info_collection){
                    isCollection=1;
                }
            }
        }

        dto.setIsSpread(isSpread);
        dto.setIsCollection(isCollection);
        //校验是否报名0否1是2审核中
        Integer isSign=  signService.check(projectId,memberId);;
        dto.setIsSign(isSign);


        //获取转发、关注的人员信息。项目详情中就各自取5条
        List<ZhongBaoProjectInfo> spreads = new ArrayList<>();

        List<ZhongBaoProjectInfo> collections = new ArrayList<>();
        for(ZhongBaoProjectInfo info:infos){
            if(spreads.size()<=5&&info.getType()==SundayCommonConstants.zhongbao_project_info_spread){
                spreads.add(info);
            }
            if(collections.size()<=5&&info.getType()==SundayCommonConstants.zhongbao_project_info_collection){
                collections.add(info);
            }
        }

        dto.setSpreads(spreads);

        dto.setCollections(collections);
        //详情中获取报名信息

        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("projectId",projectId);
        param.put("status",SundayCommonConstants.zhongbao_project_sign_ytg);
        param.put("order","desc");
        param.put("sort","ct");
        dto.setSigns(signService.list(param,5));
        //详情中标签
        ZhongBaoTag tag = tagService.getTag(0l,projectId);
        dto.setTag(tag);
        //获取项目业务员
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("projectId",projectId);
        List<ZhongBaoProjectEmployee> employees = projectEmployeeService.list(param);
        for(ZhongBaoProjectEmployee employee:employees){
            employee.setMemberImage(imgRoot+employee.getMemberImage());
        }
        dto.setEmployees(employees);
        return dto;
    }
    /**
     * 组装单个dto
     * @return
     */
    public ZhongBaoProjectDto  packageSingle(ZhongBaoProject project){
        return new ZhongBaoProjectDto(project.getId(), project.getCreateTime(),project.getCreateDate(),
                project.getName(),project.getMemberId(), project.getMemberName(), project.getMemberMobile(),
                project.getDealerId(), project.getDealerName(), project.getDealerMobile(), project.getStartDate(), project.getEndDate(),
                project.getKeyWords(), project.getDesc(), project.getStatus(), project.getType(),project.getChatGroupId(),project.getHandlerId());
    }

    /**
     * 组装多个dto
     * @param projects
     * @param memberId
     * @param isCheckCollection 是否校验收藏
     * @return
     */
    public List<ZhongBaoProjectDto>  packageMuilt(List<ZhongBaoProject> projects,Long memberId,boolean isCheckCollection){
        List<ZhongBaoProjectDto> dtos=new ArrayList<ZhongBaoProjectDto>();
        List<Long> projectIds=new ArrayList<>();
        for(ZhongBaoProject project:projects){
            projectIds.add(project.getId());
        }
        if(ListUtil.isNull(projectIds))return dtos;
        for(ZhongBaoProject project:projects){
            ZhongBaoProjectDto dto= packageSingle(project);
            dto.setIsCollection(0);
            dtos.add(dto);
        }
        if(isCheckCollection&&ListUtil.isNotNull(dtos)){
            Map<String,Object> param=new HashMap<String,Object>();
            param.put("isDeleted", SundayCommonConstants.NO);
            param.put("projectId in",projectIds);
            param.put("memberId",memberId);
            param.put("type",SundayCommonConstants.zhongbao_project_info_collection);
            List<ZhongBaoProjectInfo> infos= projectInfoService.list(param);
            for(ZhongBaoProjectDto dto:dtos){
                if(isCheckCollection){
                    for(ZhongBaoProjectInfo collection:infos){
                        if(LongUtil.isNotZreo(dto.getMemberId())&&
                                LongUtil.isNotZreo(collection.getProjectId())&&
                                LongUtil.isNotZreo(collection.getMemberId())&&
                                dto.getId()==collection.getProjectId().longValue()&&
                                dto.getMemberId().longValue()==collection.getMemberId()){
                            dto.setIsCollection(1);
                            break;

                        }
                    }
                }
            }
        }

        return dtos;
    }
    /**
     * 删除项目图片
     */
    public void deleteProjectImage(long projectId){
        projectImageService.delete(projectId);
    }


    /**
     * 项目成交
     * @param projectId
     * @param memberId
     */
    public void dealProject(long projectId,long memberId){
        ZhongBaoProject project= super.getById(projectId);
        SundayMember member= memberService.getById(memberId);
        project.setDealerId(memberId);
        project.setDealerMobile(member.getMobile());
        project.setDealerName(member.getNickName());
        project.setStatus(SundayCommonConstants.zhongbao_project_status_ycj);
        super.updateExceptEmpty(projectId,project);
    }
}
